package org.shj.basic

case class Person(name: String, age: Int)

object Email{
  def apply(user: String, domain: String) = user + "@"+ domain
  
  def unapply(str: String): Option[(String, String)] = {
    val parts = str.split("@")
    if (parts.length == 2) 
      Some(parts(0), parts(1))
    else
      None
  }
}

object Domain{
  def apply(part: String*) : String = {
    println("Domain.apply() " + part)
    part.reverse.mkString(".")
  }
  
  def unapplySeq(whole: String): Option[Seq[String]] = {
    println("whole: " + whole)
    Some(whole.split("\\.").reverse)
  }
}

object Extractor {
  def main(args: Array[String]): Unit = {
    val e = Extractor(5)  //自动调用 apply 方法
    println(e)
    
    e match{
      case Extractor(num) => println(e + " is " + num + "的两倍")
      case _ => println("无法计算")
    }
    
    println(isTomInDotCom("tom@sun.com"))
    
    val person = Person("Scala", 4) //调用了apply这个工厂构造方法创建了实例
    val Person(name, age) = person  //调用unapply方法，把person实例中的name和age提取出来并赋值给Person4这个类的成员
    println(name + ":" + age)
  }
  
  def apply(x: Int) = x*2
  
  /**
   * unapply 用于提取我们指定查找的值，它与apply的操作相反。当我们在提取器对象中使用match语句时，
   * unapply将自动执行
   */
  def unapply(z: Int) : Option[Int] = {
    if (z % 2 == 0){
      println("if")
      Some(z/2)
    }else{
      println("else")
      None
    }
  }
  
  def isTomInDotCom(s: String): Boolean = s match{
    case Email("tom", Domain("com", _*)) => true
    case _ => false
  }
}